<template>
  <div class="session-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">房间会话管理</h2>
      <div class="header-actions">
        <el-button type="danger" @click="handleEndSelectedSessions" :disabled="selectedSessions.length === 0">
          结束选中会话
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索会话ID/用户" 
        prefix-icon="Search"
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="statusFilter" placeholder="会话状态" class="filter-select">
        <el-option label="全部" value="" />
        <el-option label="活跃" value="active" />
        <el-option label="已结束" value="ended" />
      </el-select>
      <el-select v-model="typeFilter" placeholder="会话类型" class="filter-select">
        <el-option label="全部" value="" />
        <el-option label="私聊" value="private" />
        <el-option label="群聊" value="group" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <!-- 会话表格 -->
    <el-table 
      v-loading="loading" 
      :data="sessionsData" 
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="会话ID" width="150" sortable />
      <el-table-column prop="type" label="会话类型" sortable>
        <template #default="scope">
          <el-tag :type="getSessionTypeTagType(scope.row.type)">
            {{ scope.row.type === 'private' ? '私聊' : '群聊' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="participants" label="参与用户" width="250">
        <template #default="scope">
          <div class="participants-list">
            <div 
              v-for="(participant, index) in scope.row.participants.slice(0, 3)" 
              :key="participant.id"
              class="participant-item"
            >
              <el-avatar :src="participant.avatar" class="participant-avatar" />
              <span>{{ participant.username }}</span>
            </div>
            <div v-if="scope.row.participants.length > 3" class="more-participants">
              +{{ scope.row.participants.length - 3 }} 人
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="lastMessage" label="最后消息" min-width="200">
        <template #default="scope">
          <div class="last-message" :title="scope.row.lastMessage?.content">
            <span v-if="scope.row.lastMessage?.sender">
              {{ scope.row.lastMessage.sender.username }}: 
            </span>
            <span class="message-content">
              {{ formatMessageContent(scope.row.lastMessage?.content) }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="messageCount" label="消息数量" width="100" sortable />
      <el-table-column prop="status" label="会话状态" width="100" sortable>
        <template #default="scope">
          <el-tag :type="getSessionStatusTagType(scope.row.status)">
            {{ scope.row.status === 'active' ? '活跃' : '已结束' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastActivityTime" label="最后活动时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.lastActivityTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleViewSession(scope.row)">
            查看
          </el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleEndSession(scope.row.id)"
            :disabled="scope.row.status === 'ended'"
          >
            结束
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSessions"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 表格数据
const sessions = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalSessions = ref(0)
const selectedSessions = ref([])

// 搜索和筛选条件
const searchKeyword = ref('')
const statusFilter = ref('')
const typeFilter = ref('')

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化消息内容
const formatMessageContent = (content) => {
  if (!content) return '-'
  // 如果消息太长，截断显示
  return content.length > 50 ? content.substring(0, 50) + '...' : content
}

// 根据会话类型获取标签类型
const getSessionTypeTagType = (type) => {
  return type === 'private' ? 'primary' : 'success'
}

// 根据会话状态获取标签类型
const getSessionStatusTagType = (status) => {
  return status === 'active' ? 'success' : 'info'
}

// 过滤后的会话数据
const sessionsData = computed(() => {
  let filtered = [...sessions.value]
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(session => 
      session.id.toLowerCase().includes(keyword) ||
      session.participants.some(participant => 
        participant.username.toLowerCase().includes(keyword)
      )
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(session => session.status === statusFilter.value)
  }
  
  // 类型过滤
  if (typeFilter.value) {
    filtered = filtered.filter(session => session.type === typeFilter.value)
  }
  
  // 更新总数
  totalSessions.value = filtered.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 模拟加载会话数据
const loadSessionsData = () => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 生成一些模拟用户数据
    const mockUsers = Array.from({ length: 20 }, (_, i) => ({
      id: `user${i + 1}`,
      username: `user${i + 1}`,
      avatar: `https://api.dicebear.com/9.x/avataaars/svg?seed=user${i + 1}`
    }))
    
    // 生成一些模拟会话数据
    const mockSessions = Array.from({ length: 30 }, (_, i) => {
      // 随机选择2-5个参与者
      const participantCount = i % 2 === 0 ? 2 : Math.floor(Math.random() * 4) + 2
      const shuffledUsers = [...mockUsers].sort(() => 0.5 - Math.random())
      const participants = shuffledUsers.slice(0, participantCount)
      
      // 随机生成最后一条消息
      const messageTypes = ['text', 'image', 'file', 'voice']
      const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)]
      let messageContent = ''
      
      switch (messageType) {
        case 'text':
          messageContent = ['你好！', '最近怎么样？', '这个功能很棒！', '明天一起开会讨论吧', '项目进展顺利吗？', '收到请回复'][Math.floor(Math.random() * 6)]
          break
        case 'image':
          messageContent = '[图片]'
          break
        case 'file':
          messageContent = '[文件] 项目文档.pdf'
          break
        case 'voice':
          messageContent = '[语音消息 00:15]'
          break
      }
      
      return {
        id: `session_${1000 + i}`,
        type: i % 2 === 0 ? 'private' : 'group',
        participants: participants,
        messageCount: Math.floor(Math.random() * 1000) + 10,
        status: Math.random() > 0.2 ? 'active' : 'ended',
        lastMessage: {
          id: `msg_${Date.now() + i}`,
          content: messageContent,
          sender: participants[0],
          time: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString()
        },
        lastActivityTime: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString(),
        createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
      }
    })
    
    sessions.value = mockSessions
    loading.value = false
  }, 500)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  typeFilter.value = ''
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 选择会话变化
const handleSelectionChange = (selection) => {
  selectedSessions.value = selection
}

// 查看会话详情
const handleViewSession = (session) => {
  // 在实际应用中，这里会跳转到会话详情页面或打开详情弹窗
  ElMessage.info(`查看会话 ${session.id} 的详情`)
}

// 结束单个会话
const handleEndSession = (sessionId) => {
  ElMessageBox.confirm(
    '确定要结束这个会话吗？',
    '结束确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        const session = sessions.value.find(s => s.id === sessionId)
        if (session) {
          session.status = 'ended'
          ElMessage.success('会话已结束')
        }
        loading.value = false
      }, 300)
    })
    .catch(() => {
      ElMessage.info('已取消结束操作')
    })
}

// 结束选中的会话
const handleEndSelectedSessions = () => {
  if (selectedSessions.value.length === 0) {
    ElMessage.warning('请先选择要结束的会话')
    return
  }
  
  ElMessageBox.confirm(
    `确定要结束选中的 ${selectedSessions.value.length} 个会话吗？`,
    '批量结束确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        selectedSessions.value.forEach(session => {
          const s = sessions.value.find(item => item.id === session.id)
          if (s) {
            s.status = 'ended'
          }
        })
        selectedSessions.value = []
        ElMessage.success(`已成功结束 ${selectedSessions.value.length} 个会话`)
        loading.value = false
      }, 300)
    })
    .catch(() => {
      ElMessage.info('已取消批量结束操作')
    })
}

// 页面加载时初始化数据
onMounted(() => {
  loadSessionsData()
})
</script>

<style scoped>
.session-management {
  width: 100%;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索和筛选区域 */
.search-filter-section {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 120px;
}

/* 参与者列表样式 */
.participants-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.participant-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.participant-avatar {
  width: 24px;
  height: 24px;
}

.more-participants {
  color: #909399;
  font-size: 12px;
}

/* 最后消息样式 */
.last-message {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  line-height: 1.5;
}

.message-content {
  word-break: break-all;
}

/* 分页区域 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .search-input {
    width: 200px;
  }
  
  .filter-select {
    width: 100px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-filter-section {
    flex-direction: column;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
}
</style>